package xing.application.service.isv.suite;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xing.application.api.SuiteAuthApi;
import xing.application.event.isv.suite.CorpAuthSuiteES;
import xing.application.event.isv.suite.CorpAuthSuiteEvent;
import xing.domain.isv.suite.CorpApp;
import xing.domain.isv.suite.CorpSuiteAuth;
import xing.domain.isv.suite.Suite;
import xing.infrastructure.data.CallResult;
import xing.infrastructure.util.IdWorker;
import xing.repository.isv.suite.CorpAppRepository;
import xing.repository.isv.suite.CorpSuiteAuthRepository;
import xing.repository.isv.suite.SuiteRepository;
import xing.repository.isv.suite.SuiteTokenRepository;

import java.sql.Timestamp;

/*******************************************************************************************
 * 类描述：  
 *
 * @author: dustin
 * @date： 2017-8-21 18:13
 * @Description: 一句话描述该类的功能
 * @version 1.0.0
 *
 *
 * Version    Date       ModifiedBy                 Content  
 * -------- ---------    ----------         ------------------------  
 * 1.0.0     2017-8-21    Administrator                            
 *******************************************************************************************
 */
@Service
public class SuiteAuthService {
    @Autowired
    SuiteRepository suiteRepository;
    @Autowired
    SuiteTokenRepository suiteTokenRepository;
    @Autowired
    CorpSuiteAuthRepository corpSuiteAuthRepository;
    @Autowired
    CorpAppRepository corpAppRepository;

    @Autowired
    SuiteAuthApi suiteAuthApi;
    @Autowired
    CorpSuiteAuthService corpSuiteAuthService;

    @Autowired
    ApplicationContext applicationContext;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public Suite getSuiteByKey(String suiteKey){
        Suite suite= suiteRepository.findBySuiteKey(suiteKey);
        return suite;
    }

    public CallResult saveOrUpdateSuiteAuth(String suiteKey,String tmpAuthCode) {
        try{
            //1.获取套件token并存储
            String suiteToken=suiteTokenRepository.findSuiteTokenBySuiteKey(suiteKey);
            CorpSuiteAuth corpSuiteAuth=suiteAuthApi.getPermanentCode(suiteKey,tmpAuthCode,suiteToken);
            if(corpSuiteAuth==null) throw new IllegalArgumentException("获取企业套件授权信息失败");
            corpSuiteAuth.setId(IdWorker.nextId());
            Timestamp now=new Timestamp(System.currentTimeMillis());
            corpSuiteAuth.setGmtCreate(now);
            corpSuiteAuth.setGmtModified(now);
            //corpSuiteAuthRepository.save(corpSuiteAuth);
            int i= corpSuiteAuthRepository.addOrUpdateSuiteAuth(corpSuiteAuth);
            if(i>0){
                //发布授权事件
                CorpAuthSuiteES es=new CorpAuthSuiteES(corpSuiteAuth.getCorpId(),suiteKey,suiteToken,corpSuiteAuth.getPermanentCode());
                applicationContext.publishEvent(new CorpAuthSuiteEvent(this,es));
                return CallResult.ok();
            }

//            //激活
//            suiteAuthApi.activateSuite(suiteToken,suiteKey,corpSuiteAuth.getCorpId(),corpSuiteAuth.getPermanentCode());
//            //3.更新企业信息
//            corpSuiteAuthService.syncCorpInfo(suiteToken,suiteKey,corpSuiteAuth.getCorpId(),corpSuiteAuth.getPermanentCode());
            return CallResult.error("保存SuiteAuth失败");
        }catch (Exception e){
            logger.error("存储企业对套件授权信息失败:{}",e);
            return CallResult.error(e.getMessage());
        }

    }

    public CallResult activeCorpApp(String suiteKey,String corpId,String permanentCode){
        //1.获取套件token
        String suiteToken=suiteTokenRepository.findSuiteTokenBySuiteKey(suiteKey);
        //2.激活
        suiteAuthApi.activateSuite(suiteToken,suiteKey, corpId,permanentCode);


        return CallResult.ok();
    }

    @Transactional(rollbackFor=Exception.class)
    public CallResult relieveAuth(String suiteKey,String corpId){
        try {
            //1.删除掉企业对套件的授权信息
            int i = corpSuiteAuthRepository.deleteByCorpIdAndSuiteKey(corpId, suiteKey);
            //2.删除掉企业使用的微应用
            int j = corpAppRepository.deleteByCorpId(corpId);
            //4.删除企业token.这个必须删除,一旦出现解除授权立即授权的情况,之前的token是不可用的

            return CallResult.ok();
        }catch (Exception e){
            logger.error("解绑套件出错：{}",e.getMessage());
            throw e;
        }
    }

}
